package com.sqly.doc.menu.grjbxx;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.base.BaseHolder;
import com.sqly.doc.base.BaseRecyclerViewAdapter;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.ble.xty.ControlActivity;
import com.sqly.doc.pojo.BleEntity;
import com.sqly.doc.pojo.BleMeasureRecord;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.user.choose_user;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyApplication;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.ToastUtil;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.vivachek.nova.bleproxy.BleProxy;
import com.vivachek.nova.bleproxy.BluetoothBroadcastReceiver;
import com.vivachek.nova.bleproxy.annotation.BleConnectState;
import com.vivachek.nova.bleproxy.entity.BaseBluetooth;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

//import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017/11/22 0022.
 */

public class measure_xt_add extends MyBaseActivity {
    TextView kfxtz, title, uname, xm, jmid, jmsfzh, mTvResearch;
    BleMeasureRecord obj;
    Context con = measure_xt_add.this;
    JuMin j;
    private String url = "";
    boolean isadd = false;//是否是新添加
    private RecyclerView mRv;
    private BaseRecyclerViewAdapter<BleEntity> mAdapter;
    private List<String> mScanMac = new ArrayList<>();
    public static final int PERMISSION = 1;
    LinearLayout back;

    private BluetoothBroadcastReceiver mReceiver = new BluetoothBroadcastReceiver() {
        @Override
        protected void bluetoothDeviceDisconnected() {

        }

        @Override
        protected void bluetoothIsClose() {

        }

        @Override
        protected void bluetoothIsOpen() {
            BleProxy.getInstance().scan();
        }
    };
    @Override
    protected void initUI() {
        setContentView(R.layout.measure_xt_add);
        if (getIntent().getStringExtra("type").equals("edit")) {
            obj = (BleMeasureRecord) getIntent().getExtras().getSerializable("b");
            url = HttpUrl.EditGxyfsjl;
            initEditText();
            xm.setClickable(false);
        } else {
            obj=new BleMeasureRecord();
            url = HttpUrl.AddGxyfsjl;
            initEditText();
        }

        mRv = findViewById(R.id.rv);
        mTvResearch = findViewById(R.id.mTvResearch);
        mRv = findViewById(R.id.rv);
        mTvResearch.setText("正在搜索");
        mAdapter = new BaseRecyclerViewAdapter<BleEntity>(R.layout.item_search_ble) {

            @Override
            protected void convert(BaseHolder holder, BleEntity bleEntity) {
                holder.setIsRecyclable(false);
                holder.setText(R.id.tvDeviceName,
                        String.format(getString(R.string.device_name),
                                bleEntity.getBluetooth().getDevice().getName()));
                holder.setText(R.id.tvDeviceMac, String.format(getString(R.string.device_mac),
                        bleEntity.getBluetooth().getDevice().getAddress()));
                holder.setText(R.id.tvDeviceSn, String.format(getString(R.string.device_sn),
                        bleEntity.getBluetooth().getSn()));
                if (bleEntity.getState() == BleConnectState.DISCONNECTED) {
                    holder.setVisible(R.id.pb, View.GONE);
                } else if (bleEntity.getState() == BleConnectState.CONNECTING) {
                    holder.setVisible(R.id.pb, View.VISIBLE);
                    ProgressBar pb = holder.getViewById(R.id.pb);
                    pb.setIndeterminateDrawable(ActivityCompat.getDrawable(MyApplication.getApp(), R.drawable.anim_connecting));
                    pb.setProgressDrawable(ActivityCompat.getDrawable(MyApplication.getApp(),
                            R.drawable.anim_connecting));
                } else if (bleEntity.getState() == BleConnectState.CONNECT_SUCCESS) {
                    holder.setVisible(R.id.pb, View.VISIBLE);
                    ProgressBar pb = holder.getViewById(R.id.pb);
                    pb.setIndeterminateDrawable(ActivityCompat.getDrawable(MyApplication.getApp(),
                            R.drawable.connect_success));
                    pb.setProgressDrawable(ActivityCompat.getDrawable(MyApplication.getApp(),
                            R.drawable.connect_success));
                }
            }
        };
        mRv.setLayoutManager(new LinearLayoutManager(con));
        mRv.setAdapter(mAdapter);
        mRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener<BleEntity>() {
            @Override
            public void onItemClick(BaseHolder holder, BleEntity bleEntity, int position) {
                for (BleEntity entity : mAdapter.getData()) {
                    entity.setState(BleConnectState.DISCONNECTED);
                }
                bleEntity.setState(BleConnectState.CONNECTING);
                mAdapter.notifyDataSetChanged();
                BleProxy.getInstance().connect(bleEntity.getBluetooth().getDevice().getAddress());
            }
        });
        mTvResearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanBluetooth();
            }
        });
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else {
            if (requestCode == 1) {
                j = (JuMin) data.getExtras().getSerializable("j");
                getObject();
            }
            if(requestCode == 19){
                BleProxy.getInstance().stopScan();
                String deviceVal = (String) data.getExtras().getString("deviceVal");
                kfxtz.setText(deviceVal);
                mTvResearch.setText("测定完成");
                mTvResearch.setClickable(true);
            }
        }
    }

    private void initEditText() {
        xm = (TextView) findViewById(R.id.xm);
        if (obj != null && !StringUtils.isEmpty(obj.getJmname())) {
            xm.setText(obj.getJmname());
        } else {
            xm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivityForResult(new Intent(con, choose_user.class).putExtra("cname", "measure_xt_add.class"), 1);
                }
            });
        }
        jmid = (TextView) findViewById(R.id.jmid);
        jmsfzh = (TextView) findViewById(R.id.jmsfzh);
        //空腹血糖值
        kfxtz = (TextView) findViewById(R.id.kfxtz);
        kfxtz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String xtyval = (String) SharedPreferencesUtils.getParam(con, "xtyval", "");
                if(null == xtyval || "".equals(xtyval)) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请先绑定蓝牙血糖仪设备");
                }else if (obj != null && StringUtils.isEmpty(obj.getJmname())) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击用户输入框选择用户");
                } else {
                    for (BleEntity entity : mAdapter.getData()) {
                        entity.setState(BleConnectState.DISCONNECTED);
                        if(xtyval.equals(entity.getBluetooth().getDevice().getAddress()) ){
                            entity.setState(BleConnectState.CONNECTING);
                            BleProxy.getInstance().connect(entity.getBluetooth().getDevice().getAddress());
                            break;
                        }
                    }
                }
            }
        });
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("居民血糖值测定");
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (obj == null)
                    obj = new BleMeasureRecord();
                obj.setVal1(kfxtz.getText().toString());

                if (null == xm.getText().toString() || xm.getText().toString().equals("")) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击用户输入框选择用户");
                } else if (null == kfxtz.getText().toString() || kfxtz.getText().toString().equals("")) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击血糖值输入框进行血糖值测量");
                } else if (NetWorkUtils.isNetworkConnected(con)) {
                    RequestParams ps = new RequestParams();
                    ps.add("entity.category", "1");
                    ps.add("entity.jmid", obj.getJmid());
                    ps.add("entity.jmname", obj.getJmname());
                    ps.add("entity.jmsfzh", obj.getJmsfzh());
                    ps.add("entity.val1", obj.getVal1());
                    ps.add("entity.val2", "0");
                    ps.add("entity.val3", "0");
                    ps.add("entity.blename", obj.getBlename());
                    ps.add("entity.blemac", obj.getBlemac());
                    ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                    ps.add("type", "2");
                    if (isadd) {
                        url = HttpUrl.AddBleMRecord;
                    } else {
                        ps.add("entity.id", obj.getRid());
                        url = HttpUrl.SaveBleMRecord;
                    }
                    UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                            String content = new String(response);
                            RetMsg ret = JSON.parseObject(content, RetMsg.class);
                            if (ret.getCode().equals("200")) {
                                MyToastUtil.ShowToast(con, "成功");
                            }else{
                                MyToastUtil.ShowToast(con, ret.getInfo());
                            }
                            finish();
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                            MyToastUtil.ShowToast(con, "失败");
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    public void getObject() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("CARDNUM", j.getCARDNUM());
        UserClient.get(HttpUrl.GetXxfhGrjbxx, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                Log.i("ycf2", content);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    if (StringUtils.isEmpty(ret.getOtherParams())) {//other是空的
                        JSONObject j = JSON.parseObject(ret.getRd());
                        obj = new BleMeasureRecord();
                        obj.setJmid(j.getString("JKDAH"));
                        obj.setJmname(j.getString("XINGMING"));
                        obj.setJmsfzh(j.getString("SFZH"));
                        xm.setText(j.getString("XINGMING"));
                        jmid.setText(j.getString("JKDAH"));
                        jmsfzh.setText(j.getString("SFZH"));
                        isadd = true;
                    } else {
                        obj = JSON.parseObject(ret.getRd(), BleMeasureRecord.class);
                    }
                } else {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", ret.getInfo());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                isadd = true;
                obj = new BleMeasureRecord();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
//		监视蓝牙关闭和打开的状态
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
//		监视蓝牙设备与APP连接的状态
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(mReceiver,filter);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int bluetooth = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
            int bluetoothAdmin = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.BLUETOOTH_ADMIN);
            int location = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION);
            if (bluetooth == PackageManager.PERMISSION_GRANTED && bluetoothAdmin == PackageManager.PERMISSION_GRANTED && location == PackageManager.PERMISSION_GRANTED) {
                scanBluetooth();
            } else {
                requestPermissions(new String[]{Manifest.permission.BLUETOOTH,
                        Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION);
            }

        }else {
            scanBluetooth();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }
    private void scanBluetooth() {
        mScanMac.clear();
        mAdapter.clearData();
        mAdapter.notifyDataSetChanged();
        if (BleProxy.getInstance().isBleEnable()) {
            BleProxy.getInstance().scan();
        }else {
            BleProxy.getInstance().enableBle();
        }
    }

    @Override
    public void onScanStart() {
        super.onScanStart();
        mTvResearch.setText(getString(R.string.searching));
        mTvResearch.setClickable(false);
    }

    @Override
    public void onScanFinish(List<BaseBluetooth> scanResultList) {
        super.onScanFinish(scanResultList);
        if(null != mTvResearch.getText() && !"设备正常".equals(mTvResearch.getText())) {
            mTvResearch.setText(getString(R.string.research));
        }
        mTvResearch.setClickable(true);
    }

    @Override
    public void onScanning(BaseBluetooth bleDevice) {
        Log.i("onScanning","================2");
        super.onScanning(bleDevice);
        if (bleDevice == null) {
            return;
        }
        String mac = bleDevice.getDevice().getAddress();
        String name = bleDevice.getDevice().getName();
        if (TextUtils.isEmpty(mac) || TextUtils.isEmpty(name)) {
            return;
        }
        BleEntity bleEntity = new BleEntity(bleDevice, BleConnectState.DISCONNECTED);
        boolean isNotify = false;
        if (mScanMac.contains(mac)) {
            for (BleEntity entity : mAdapter.getData()) {
                if (entity.getBluetooth().getDevice().getAddress().equals(mac)) {
                    String sn = entity.getBluetooth().getSn();
                    if (TextUtils.isEmpty(sn)) {
                        entity.getBluetooth().setSn(bleDevice.getSn());
                        isNotify = true;
                        break;
                    }
                }
            }
            if (isNotify) {
                mAdapter.notifyDataSetChanged();
            }
        } else {
            mScanMac.add(mac);
            mAdapter.addData(bleEntity);
            mAdapter.notifyDataSetChanged();
        }
        String xtyval = (String) SharedPreferencesUtils.getParam(con, "xtyval", "");
        if(null == xtyval || "".equals(xtyval)) {
            SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击用户输入框选择用户");
        }else {
            for (BleEntity entity : mAdapter.getData()) {
                if (xtyval.equals(entity.getBluetooth().getDevice().getAddress())) {
                    mTvResearch.setText("设备正常");
                    break;
                }
            }
        }
    }

    @Override
    public void onConnectSuccess(BaseBluetooth bleDevice) {
        Log.i("onConnectSuccess","================1");
        super.onConnectSuccess(bleDevice);
        for (BleEntity entity : mAdapter.getData()) {
            if (entity.getBluetooth().getDevice().getAddress().equals(bleDevice.getDevice().getAddress())) {
                entity.setState(BleConnectState.CONNECT_SUCCESS);
            } else {
                entity.setState(BleConnectState.DISCONNECTED);
            }
        }
        mAdapter.notifyDataSetChanged();
        BleProxy.getInstance().notify(bleDevice);

    }

    @Override
    public void openNotifySuccess(BaseBluetooth bleDevice) {
        Log.i("openNotifySuccess","================3");
        super.openNotifySuccess(bleDevice);
        Intent intent = new Intent(this, ControlActivity.class);
        intent.putExtra(ControlActivity.DEVICE, (Serializable) bleDevice);
        startActivityForResult(intent, 19);
    }

    @Override
    public void openNotifyFail() {
        super.openNotifyFail();
        for (BleEntity entity : mAdapter.getData()) {
            entity.setState(BleConnectState.DISCONNECTED);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onConnectFail(String mac) {
        super.onConnectFail(mac);
        for (BleEntity entity : mAdapter.getData()) {
            entity.setState(BleConnectState.DISCONNECTED);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showShortToast(MyApplication.getApp(), getString(R.string.permission_denied));
                    return;
                }
            }
            scanBluetooth();
        } else {
            ToastUtil.showShortToast(MyApplication.getApp(), getString(R.string.permission_denied));
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
